﻿using System;
using K9Nano.Caching;
using K9Nano.Domain.Organization;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.Extensions.DependencyInjection;

namespace K9Nano.Domain.Caching;

public class OrganizationUnitCacheBase<TDbContext>(IServiceProvider serviceProvider,
    ITypedCache<OrganizationUnitCacheInfo> cache) : IOrganizationUnitCache 
    where TDbContext : DbContext
{
    public virtual OrganizationUnitCacheInfo? Get(long id)
    {
        if (id <= 0) return null;
        var key = id.ToString();
        var info = cache.Get(key);
        if (info is null)
        {
            info = GetInternal(id);
            if (info != null)
            {
                cache.Add(key, info, TimeSpan.FromMinutes(10));
            }
        }
        return info;
    }

    protected virtual OrganizationUnitCacheInfo? GetInternal(long id)
    {
        using var scope = serviceProvider.CreateScope();
        var db = scope.ServiceProvider.GetRequiredService<TDbContext>();
        var ou = db.Set<OrganizationUnit>().AsNoTracking()
            .FirstOrDefault(a => a.Id == id);
        if (ou is null) return null;
        return new OrganizationUnitCacheInfo(ou.Id, ou.Code, ou.DisplayName, ou.Tag, ou.Extension, ou.ParentId);
    }
}
